package com.example.homework7;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.List;

public class rm extends Fragment {
    private EditText editTextTextPersonName9,editTextTextPersonName7,editTextTextPersonName8;
    private Button button9,button10;
    private TextView textView3;
    public rm(){
        super(R.layout.rm);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        EditText editTextTextPersonName7=(EditText) getView().findViewById(R.id.editTextTextPersonName7);
        EditText editTextTextPersonName8=(EditText) getView().findViewById(R.id.editTextTextPersonName8);
        EditText editTextTextPersonName9=(EditText) getView().findViewById(R.id.editTextTextPersonName9);
        Button button9=(Button) getView().findViewById(R.id.button9);
        Button button10=(Button) getView().findViewById(R.id.button10);
        textView3=(TextView) getView().findViewById(R.id.textView3);


        MyRoomDatabase db = MyRoomDatabase.getInstance(getActivity());
        button9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                User user=new User();
                user.id=Integer.parseInt(editTextTextPersonName7.getText().toString());
                user.username=editTextTextPersonName8.getText().toString();
                user.age= Integer.parseInt(editTextTextPersonName9.getText().toString());
                db.userDao().insert(user);
                Toast.makeText(getActivity(),"添加成功",Toast.LENGTH_SHORT).show();

            }
        });
       button10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                showUsers(db.userDao().searchUsersByAge(18));
            }
        });


    }
    private void showUsers(List<User> users){
        StringBuilder stringBuilder=new StringBuilder();
        for(User user:users){
            stringBuilder.append("id: ").append(user.id)
                    .append("  username: ").append(user.username)
                    .append("  age: ").append(user.age)
                    .append("\n");
        }
        textView3.setText(stringBuilder.toString());
    }

}
